package com.example.close_order.controller;

import com.example.close_order.entity.Order;
import com.example.close_order.service.OrderCloseService;
import com.example.close_order.service.OrderService;
import com.example.close_order.scheduler.OrderCloseScheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/orders")
public class OrderController {
    
    @Autowired
    private OrderService orderService;
    
    @Autowired
    private OrderCloseService orderCloseService;
    
    @Autowired
    private OrderCloseScheduler orderCloseScheduler;
    
    /**
     * 创建订单并设置自动关闭时间
     */
    @PostMapping
    public ResponseEntity<Map<String, Object>> createOrder(@RequestBody CreateOrderRequest request) {
        try {
            Order order = orderService.createOrder(
                    request.getUserId(),
                    request.getAmount(),
                    request.getCloseTimeoutMinutes()
            );
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("orderNo", order.getOrderNo());
            response.put("message", "订单创建成功");
            response.put("expireTime", order.getExpireTime());
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "订单创建失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 手动关闭订单（用于测试和管理）
     */
    @PostMapping("/{orderNo}/close")
    public ResponseEntity<Map<String, Object>> closeOrder(@PathVariable String orderNo) {
        try {
            boolean success = orderCloseService.closeOrder(orderNo);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", success);
            response.put("message", success ? "订单关闭成功" : "订单关闭失败");
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "订单关闭异常: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 取消订单关闭任务（例如用户支付后）
     */
    @PostMapping("/{orderNo}/cancel-close")
    public ResponseEntity<Map<String, Object>> cancelOrderClose(@PathVariable String orderNo) {
        try {
            boolean success = orderCloseScheduler.cancelOrderCloseTask(orderNo);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", success);
            response.put("message", success ? "订单关闭任务取消成功" : "订单关闭任务取消失败");
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "取消订单关闭任务异常: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 获取订单状态
     */
    @GetMapping("/{orderNo}")
    public ResponseEntity<Map<String, Object>> getOrderStatus(@PathVariable String orderNo) {
        try {
            Order order = orderService.getOrderByNo(orderNo);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("order", order);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取订单信息失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 创建订单请求体
     */
    public static class CreateOrderRequest {
        private Long userId;
        private BigDecimal amount;
        private Integer closeTimeoutMinutes = 30; // 默认30分钟
        
        // Getter和Setter
        public Long getUserId() { return userId; }
        public void setUserId(Long userId) { this.userId = userId; }
        
        public BigDecimal getAmount() { return amount; }
        public void setAmount(BigDecimal amount) { this.amount = amount; }
        
        public Integer getCloseTimeoutMinutes() { return closeTimeoutMinutes; }
        public void setCloseTimeoutMinutes(Integer closeTimeoutMinutes) { 
            this.closeTimeoutMinutes = closeTimeoutMinutes; 
        }
    }
}